﻿using System;
using System.Collections.Specialized;
using System.Text;
using AllInOnePluginBL;
using AllInOnePluginBL.Helpers;
using PluginDB;
using Rss;

public partial class PluginService : System.Web.UI.Page
{
    private FavouritsHandler favouritsHandler;
    private string action;
    private string userName;
    private string password;
    private long seriesId;
    private PluginMode pluginMode;
    private int videoId;

    private enum PluginMode
    {
        MOVIES_MODE=1,
        SERIES_MODE
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        RssFeed rssFeed;

        try
        {
            this.favouritsHandler = new FavouritsHandler();

            InitMembers(this.Request.QueryString);

            var user = this.ValidateInputAndGetUser() ?? favouritsHandler.CreateUser(this.userName, this.password);

            switch (pluginMode)
            {
                case PluginMode.SERIES_MODE:
                    {
                        rssFeed = HandleSeriesMode(user);
                        break;
                    }
                case PluginMode.MOVIES_MODE:
                    {
                        rssFeed = HandleMoviesMode(user);
                        break;
                    }
                default:
                    {
                        rssFeed = CreateResponse(false, "Got invalid parameters");
                        break;
                    }
            }
            
        }
        catch (Exception ex)
        {
            rssFeed = CreateResponse(false, ex.Message);
        }

        this.Response.Clear();
        this.Response.ContentType = "text/xml";
        rssFeed.Write(this.Response.OutputStream);
        this.Response.End();
    }

    private void InitMembers(NameValueCollection queryStringParams)
    {
        this.action = Utils.GetParam(queryStringParams, AllInOnePluginBL.Helpers.Common.ACTION, string.Empty);
        this.pluginMode = (PluginMode)Utils.GetParam(queryStringParams, AllInOnePluginBL.Helpers.Common.PLUGIN_MODE, 0);
        this.userName = Utils.GetParam(queryStringParams, AllInOnePluginBL.Helpers.Common.USER_NAME, string.Empty);
        this.password = Utils.GetParam(queryStringParams, AllInOnePluginBL.Helpers.Common.USER_PASSWORD, string.Empty);
        this.seriesId = Utils.GetParam(queryStringParams, AllInOnePluginBL.Helpers.Common.SERIES_ID, 0);
        this.videoId = Utils.GetParam(queryStringParams, AllInOnePluginBL.Helpers.Common.VIDEO_ID, 0);
    }

    private User ValidateInputAndGetUser()
    {
        if (string.IsNullOrEmpty(this.action))
            throw new Exception("No action givven");
        
        //Check userName and password
        if(string.IsNullOrEmpty(this.userName))
            throw new Exception("The userName is empty");

        if(string.IsNullOrEmpty(this.password))
            throw new Exception("The password  is empty");

        var user = this.favouritsHandler.GetUser(this.userName, this.password);
        
        //Check series
        if (this.pluginMode ==PluginMode.SERIES_MODE && this.seriesId == 0 && this.videoId == 0)
            throw new Exception("The seriesId or videoId is not valid");
        
        return user;
    }

    private RssFeed HandleSeriesMode(User user)
    {
        RssFeed rssFeed = null;

        if (this.action.ToLower().Equals("add"))
        {
            if(this.videoId != 0)
            {
                this.seriesId = favouritsHandler.GetSeriesIdFromVideoId(this.videoId);
            }
            rssFeed = CreateResponse(favouritsHandler.AddSeriesToFavourits(user, this.seriesId), string.Empty);
        }
        else if (this.action.ToLower().Equals("remove"))
        {
            if (this.videoId != 0)
            {
                this.seriesId = favouritsHandler.GetSeriesIdFromVideoId(this.videoId);
            }
            rssFeed = CreateResponse(favouritsHandler.RemoveSeriesFromFavourits(user, this.seriesId), string.Empty);
        }
        return rssFeed;
    }

    private RssFeed HandleMoviesMode(User user)
    {
        RssFeed rssFeed = null;

        if (this.action.ToLower().Equals("add"))
        {
            rssFeed = CreateResponse(favouritsHandler.AddVideoToFavourits(user, this.videoId), string.Empty);
        }
        else if (this.action.ToLower().Equals("remove"))
        {
            rssFeed = CreateResponse(favouritsHandler.RemoveVideoFromFavourits(user, this.videoId), string.Empty);
        }
        return rssFeed;
    }

    private RssFeed CreateResponse(bool isItemSaved, string errorMessage)
    {
        var rssChannel = new RssChannel
        {
            Title = "Movies Channel",
            Description = "Movies List",
            Link = new Uri(string.Format("{0}", Utils.GetSiteUrl())),
            Language = "he"
        };
        rssChannel.LastBuildDate = rssChannel.Items.LatestPubDate();

        if (isItemSaved)
        {
            var rssItem = new RssItem
            {
                Title = "Item Added",
                Description = "Item Added",
                PubDate = DateTime.Now,
                Link = new Uri(string.Format("{0}", Utils.GetSiteUrl()))
            };

            rssChannel.Items.Add(rssItem);
        }
        else
        {
            var rssItem = new RssItem
            {
                Title = "Item Not Saved",
                Description = errorMessage,
                PubDate = DateTime.Now,
                Link = new Uri(string.Format("{0}", Utils.GetSiteUrl()))
            };

            rssChannel.Items.Add(rssItem);
        }
        var rssFeed = new RssFeed { Encoding = Encoding.UTF8 };
        rssFeed.Channels.Add(rssChannel);
        return rssFeed;
    }
}